package com.xingfei.blog.controller.ThirdLoginController;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.xingfei.blog.common.JsonResult;
import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.dto.UserInfoDTO;
import com.xingfei.blog.redisCluster.RedisClusterUtil;
import com.xingfei.blog.service.WebUserService;
import com.xingfei.blog.utils.*;
import com.xingfei.blog.vo.UserVO;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import weibo4j.Account;
import weibo4j.Oauth;
import weibo4j.http.AccessToken;
import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;
import weibo4j.util.WeiboConfig;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 第三方登陆接口，weibo
 * Created by yhang on 2017/3/1.
 */
@Controller
@RequestMapping("/login")
public class WeiboLogin {

    private static Logger logger = LoggerFactory.getLogger(WeiboLogin.class);

    @Autowired
    private WebUserService webUserService;

    private static String Profix_weibo = "weibo:";

    private static String Profix_User = "user:";

    private String REMOTE_URL="http://jianyiblog.com:8808/web-upload/uploadFile/uploadByUrl";

    @Autowired
    private RedisClusterUtil redisCluster;

    @Value("${spring.activemq.broker-url}")
    private String brokerurl;

    @Value("${spring.activemq.user}")
    private String username;

    @Value("${spring.activemq.password}")
    private String password;

    /**
     * weibo_login
     */
    @RequestMapping(value = "/weibo",method = RequestMethod.GET)
    public String getCode(@RequestParam("code") String code, HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map = new HashMap<String, Object>();
        try {
            //获取accesstoken 对象
            Oauth oauth = new Oauth();
            AccessToken accessToken = oauth.getAccessTokenByCode(code);
            String access_token = accessToken.getAccessToken();
            //获取uid
            Account am = new Account(access_token);
            JSONObject uidObject = am.getUid();
            String weibo_uid = uidObject.getString("uid");
            map.put("weibo_uid",weibo_uid);
            //获取weibo信息
            User userWeiboInfo = webUserService.getUserWeiboInfo(access_token, weibo_uid);
            //判断是否已经绑定用户
            Long userId = webUserService.getUserInfoByWeiboUid(weibo_uid);
            if(userId==null){
                //与注册的用户进行绑定绑定，跳转到绑定界面
                //获取用户所在ip
                String ip = IPUtil.getLocalIp(request);
                //将从qq获取的信息缓存redis
                UserInfoDTO userinfo = new UserInfoDTO();
                //用户名
                userinfo.setUserName(userWeiboInfo.getScreenName());
                //weibo头像转换存储
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(REMOTE_URL+"?remoteUrl="+userWeiboInfo.getProfileImageURL());
                CloseableHttpResponse execute = httpClient.execute(httpGet);
                HttpEntity entity = execute.getEntity();
                String requestResult = EntityUtils.toString(entity);
                if(StringUtils.isNotEmpty(requestResult)){
                    userinfo.setAvatarUrl(requestResult);
                }else {
                    //存储异常还是保存原始url
                    userinfo.setAvatarUrl(userWeiboInfo.getProfileImageURL()+"");
                }
                userinfo.setWeiboUid(weibo_uid);
                //注册ip
                userinfo.setRegisterIp(ip);
                //用户地址
                if(StringUtils.isNotEmpty(userWeiboInfo.getLocation())){
                    userinfo.setAddress(userWeiboInfo.getLocation());
                }
                //描述
                if(StringUtils.isNotEmpty(userWeiboInfo.getDescription())){
                    userinfo.setDescription(userWeiboInfo.getDescription());
                }
                //用户性别
                if(StringUtils.isNotEmpty(userWeiboInfo.getGender()) && userWeiboInfo.getGender()!="n"){
                    userinfo.setSex(userWeiboInfo.getGender().equals("m")?"1":"2");
                }

                String value = JSON.toJSONString(userinfo);
                String token = MD5Util.getMD5(weibo_uid);
                //RedisUtil.set(Profix_weibo + token, value, Integer.valueOf(60*30), null);
                redisCluster.set(Profix_weibo + token, value, Integer.valueOf(60*30));
                CookieUtil.setCookieDefault(response,"token_weibo",token);
                return "login/jianyi-login-weibo";
            }else{
                UserVO user = webUserService.getUserAndUserInfoById(userId);
                //设置缓存
                String ip = IPUtil.getLocalIp(request);
                String token = MD5Util.getMD5(ip + System.currentTimeMillis());
                //校验通过，保存进redis
                String value = JSON.toJSONString(user);
                //30分钟
                //RedisUtil.set(Profix_User + token, value, Integer.valueOf(60 * 30), 1);
                redisCluster.set(Profix_User + token, value, Integer.valueOf(60 * 30));
                CookieUtil.setCookieDefault(response, "token", token);
                //用户信息保存当前线程中
                UserThreadLocal.set(user);
                //若已经做过绑定,直接登陆
                webUserService.firstToLoad(request, user);
            }
                return "index";

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (WeiboException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
            return null;
    }

    /**
     * 获取调用weibo的url
     * @return
     */
    @RequestMapping(value = "/redirectWeiboUrl",method = RequestMethod.GET)
    public @ResponseBody JsonResult getWeibUrl(){
        JsonResult jsonResult = null;
        try {
            String client_id = WeiboConfig.getValue("client_ID");
            String redirect_uri = WeiboConfig.getValue("redirect_URI");
            String authorizeURL = WeiboConfig.getValue("authorizeURL");
            String url =authorizeURL+"?client_id="+client_id+"&redirect_uri="+redirect_uri+"&response_type=code";
            jsonResult = new JsonResult(false, ErrorConstants.SERVER_SUCCESS, url);
        } catch (Exception e) {
            jsonResult = new JsonResult(false, ErrorConstants.SERVER_ERROR, "服务器错误");
        }
        return jsonResult;
    }
    @RequestMapping("/bindWeiBo")
    public String bindQQ(){
        return "/login/jianyi-login-weibo-bind";
    }

    /**
     * weibo注册
     * @param request
     * @return
     */
    @RequestMapping("/weiboRegist")
    public @ResponseBody JsonResult weiboRegist(HttpServletRequest request,HttpServletResponse response){
        JsonResult jsonResult = null;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            try {
                Cookie cookie2 = CookieUtil.getCookie(request, "token_weibo");
                if(cookie2!=null){
                    String token = cookie2.getValue();
                    if(StringUtils.isNotEmpty(token)){
                        //UserInfoDTO userDTO = JSON.parseObject(RedisUtil.get(Profix_weibo + cookie2.getValue(), null), UserInfoDTO.class);
                        UserInfoDTO userDTO = JSON.parseObject(redisCluster.get(Profix_weibo + cookie2.getValue()), UserInfoDTO.class);
                        //注册生成用户和详情表
                        boolean flag = webUserService.thirdRegistAndSaveUserInfo(userDTO,request,response);
                        if(flag){
                            jsonResult = new JsonResult(ErrorConstants.SERVER_SUCCESS, "success");

                        }else {
                            jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR, "注册失败，请重试！");
                        }
                    }
                }

            }catch (Exception e){
                logger.error("qqRegist error:",e);
                jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR, "注册失败，请重试！");
                return jsonResult;
            }
        }
        return jsonResult;
    }
}
